<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="150px" v-loading="formLoading">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="年份" prop="years">
            <el-date-picker
              v-model="yearValue"
              type="year"
              format="YYYY"
              value-format="YYYY"
              placeholder="选择年份"
              class="!w-full"
              @change="handleYearChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="季度" prop="quarter">
            <el-select v-model="formData.quarter" placeholder="请选择季度" class="!w-full">
              <el-option label="第一季度" :value="1" />
              <el-option label="第二季度" :value="2" />
              <el-option label="第三季度" :value="3" />
              <el-option label="第四季度" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="员工" prop="userId">
            <UserSelect v-model="formData.userId" @node-change="onUserChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考核奖金基准金额" prop="baseBonusAmount">
            <el-input-number
              v-model="formData.baseBonusAmount"
              :precision="2"
              :min="0"
              placeholder="请输入考核奖金基准金额"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="考核总分" prop="totalScore">
            <el-input-number
              v-model="formData.totalScore"
              :precision="2"
              :min="0"
              placeholder="请输入考核总分"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="季度奖金金额" prop="quarterlyBonusAmount">
            <el-input-number
              v-model="formData.quarterlyBonusAmount"
              :precision="2"
              :min="0"
              placeholder="请输入季度奖金金额"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="formData.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { EmployeeQuarterlyAssessmentApi, EmployeeQuarterlyAssessmentVO } from '@/api/oa/employeequarterlyassessment'
import UserSelect from '@/views/system/user/UserSelect.vue'

/** 员工季度考核 表单 */
defineOptions({ name: 'EmployeeQuarterlyAssessmentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const yearValue = ref<string>() // 年份选择器的值(字符串类型)
const formData = ref({
  id: undefined,
  years: undefined,
  quarter: undefined,
  userId: undefined,
  userName: undefined,
  baseBonusAmount: undefined,
  totalScore: undefined,
  quarterlyBonusAmount: undefined,
  status: undefined,
  remarks: undefined,
})
const formRules = reactive({
  years: [{ required: true, message: '年份不能为空', trigger: 'blur' }],
  quarter: [{ required: true, message: '季度不能为空', trigger: 'change' }],
  userId: [{ required: true, message: '员工不能为空', trigger: 'blur' }],
  userName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 年份改变处理 */
const handleYearChange = (value: string | null) => {
  if (value) {
    formData.value.years = parseInt(value)
  } else {
    formData.value.years = undefined
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await EmployeeQuarterlyAssessmentApi.getEmployeeQuarterlyAssessment(id)
      formData.value = data
      // 将数字类型的years转换为字符串供日期选择器显示
      if (formData.value.years) {
        yearValue.value = formData.value.years.toString()
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as EmployeeQuarterlyAssessmentVO
    if (formType.value === 'create') {
      await EmployeeQuarterlyAssessmentApi.createEmployeeQuarterlyAssessment(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeQuarterlyAssessmentApi.updateEmployeeQuarterlyAssessment(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  yearValue.value = undefined
  formData.value = {
    id: undefined,
    years: undefined,
    quarter: undefined,
    userId: undefined,
    userName: undefined,
    baseBonusAmount: undefined,
    totalScore: undefined,
    quarterlyBonusAmount: undefined,
    status: undefined,
    remarks: undefined,
  }
  formRef.value?.resetFields()
}

/** 用户选择回调 */
const onUserChange = (user: any) => {
  formData.value.userId = user?.id
  formData.value.userName = user?.nickname
}
</script>
